package ar.unq.edu.svnpermission.homes;

import java.util.List;
import java.util.ArrayList;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.uqbar.commons.home.db4o.DB4OHomeImpl;
import org.uqbar.commons.model.CollectionBasedHome;

import ar.edu.unq.svnpermission.domain.Folder;
import ar.edu.unq.svnpermission.domain.User;
import ar.unq.edu.svnpermission.utils.Validator;


/**
 * @author nicolas
 *
 */
public class FolderHome  extends DB4OHomeImpl<Folder> {

	public FolderHome(Class<Folder> entityType) {
		super(entityType);
		// TODO Auto-generated constructor stub
	}


	public Class<Folder> getEntityType() {
		// TODO Auto-generated method stub
		return null;
	}


	public Folder createExample() {
		return new Folder();
	}


	protected Predicate getCriterio( final Folder example) {
		return new Predicate() {
			public boolean evaluate(Object arg) {
				Folder contact = (Folder) arg; 
				//Devuelvo true solo si el Path es igual
				return (Validator.matchWithString(contact.getFullPath(),example.getFullPath()));
				 
			}
		};
	}
	
	/**
	 * Obtiene el criterio para determinar si una Carpeta es Root
	 * @return Un predicate
	 */
	private Predicate getRootFolderCriteria() {
		return new Predicate() {
			public boolean evaluate(Object arg) {
				if(arg.getClass()!=Folder.class)
					return false;
				Folder folder = (Folder) arg; 
				if(folder==null)
					return false;
				return (folder.getParent()==null);
				 
			}
		};
	}	
	
	/**
	 * Obtiene la Carpeta Root.
	 * @return Un Folder que representa la carpeta Root
	 * @author nicolas
	 */
	@SuppressWarnings("unchecked")
	public Folder getRootFolder() {
		List<Folder> folders = (List<Folder>)CollectionUtils.select(this.allInstances(), this.getRootFolderCriteria());
		Folder folder = null;
		if(!folders.isEmpty())
		{
			folder = folders.get(0);
		}
		else
		{
			folder = new Folder();
			folder.setName("ROOT");
		}
		return folder;
	}

}
